package com.hitalkie.teacher.adapter;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.hitalkie.teacher.R;
import com.hitalkie.teacher.model.Country;

import java.util.ArrayList;
import java.util.List;

/**
 * Date 16/11/2016
 *
 * @author charliema
 */

public class CountryRvAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {


    private List<Country> mData = new ArrayList<>();

    private OnItemClickListener mOnItemClick;

    public void setData(List<Country> list) {
        if (list != null) {
            this.mData = list;
        }
        notifyDataSetChanged();
    }

    public void addData(List<Country> list) {
        if (list != null) {
            this.mData.addAll(list);
        }
        notifyDataSetChanged();
    }

    public void setOnItemClickListener(OnItemClickListener onItemClick) {
        mOnItemClick = onItemClick;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(parent);
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
        ((ViewHolder) holder).bindData(mData.get(holder.getAdapterPosition()));
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    /**
     * view holder
     */
    private class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvCountryName;
        TextView tvPhoneRegionCode;

        ViewHolder(ViewGroup parent) {
            super(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_country, parent, false));

            tvCountryName = (TextView) itemView.findViewById(R.id.tvCountryName);
            tvPhoneRegionCode = (TextView) itemView.findViewById(R.id.tvPhoneRegionCode);
        }

        void bindData(final Country data) {
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mOnItemClick != null) {
                        mOnItemClick.onItemClick(data);
                    }
                }
            });
            tvCountryName.setText(data.getName());
            tvPhoneRegionCode.setText(data.area_code);
        }
    }

    /**
     * click event
     */
    public interface OnItemClickListener {
        void onItemClick(Country data);

    }
}
